package com.wxsong.authplatform.authweb.service.authority;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.wxsong.authplatform.authweb.dao.authority.AuthorityDao;
import com.wxsong.authplatform.authweb.exception.InstantException;
import com.wxsong.authplatform.authweb.model.authority.Authority;
import com.wxsong.authplatform.authweb.model.menu.Menu;
import com.wxsong.authplatform.authweb.util.ObjectUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

@Service
@Transactional(rollbackFor = Exception.class)
public class AuthorityServiceImpl implements AuthorityService {

    @Resource
    private AuthorityDao authorityDao;

    @Override
    @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
    public Authority getByName(String name) {
        return authorityDao.getByName(name);
    }

    @Override
    public List<Authority> list(int from, int pageSize, Map<String, Object> paramMap) {
        return authorityDao.list(from, pageSize, paramMap);
    }

    @Override
    public Long count(Map<String, Object> paramMap) {
        return authorityDao.count(paramMap);
    }

    @Override
    public int add(Authority authority) {
        return authorityDao.add(authority);
    }

    @Override
    public int updateInfo(Long id, String name){
        Map paramMap = Maps.newHashMap();
        paramMap.put("id", id);
        paramMap.put("name", name);
        return authorityDao.update(paramMap);
    }

    @Override
    public int delete(Long[] ids) {
        return authorityDao.delete(ids);
    }

    @Override
    public Authority getById(Long id) {
        return authorityDao.getById(id);
    }

    @Override
    public List<Menu> hasMenus(Long[] ids) {
        if(ids == null || ids.length < 1){
            return Lists.newArrayList();
        }
        return authorityDao.hasMenus(ids);
    }

    @Override
    public List<Menu> noMenus(Long[] ids) {
        return authorityDao.noMenus(ids);
    }

    @Override
    public int modifyMenus(String ids, Long roleId){
        Authority authority = authorityDao.getById(roleId);
//        authority.modifyMenus(ids);
        Map paramMap = null;
        try {
            paramMap = ObjectUtil.toMap(authority);
        } catch (Exception e) {
            throw new InstantException("修改权限数据时，对象转换为map出现异常", e);
        }
        return authorityDao.update(paramMap);
    }


}
